﻿from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save, post_delete
from django.core.cache import cache
from geography.models import L0Object, L1Object, L2Object, L34Object, Place
from organization.models import Position

GENDER = {u'M': u'мужской', u'F': u'женский',}
MARITAL = { u'M': u'замужем', u'R': u'встречается', u'N': u'не замужем',}
POLITICAL = {u'D': u'демократические', u'S': u'социалистические',}
RELIGIOUS = {u'': u'', u'': u'', u'': u'', u'': u'',}

GENDER_CHOICES = tuple(GENDER.items())
MARITAL_CHOICES = tuple(MARITAL.items())
POLITICAL_CHOICES = tuple(POLITICAL.items())
RELIGIOUS_CHOICES = tuple(RELIGIOUS.items())

class Friendship(models.Model):
        
        
    _from = models.ForeignKey('UserProfile', related_name='friendship_sender')
    _to = models.ForeignKey('UserProfile', related_name='friendship_receiver')
    
    def get_count(to_id):
        cache_key = 'new_freindships_count_for_%s' % (to_id)
        count = cache.get(cache_key)
        if count is None:
            from django.db import connection
            query = 'SELECT COUNT(id) FROM userprofile_friendship WHERE userprofile_friendship._to_id = %s' % (str(to_id))
            cursor = connection.cursor()
            cursor.execute(query)
            count = cursor.fetchone()
            cache.set(cache_key, count)
        return count
    get_count = staticmethod(get_count)
    
    def __unicode__(self):
        return self._from.get_full_name() + u' \u2192 ' + self._to.get_full_name()
    
    #class Meta:
        #unique_together = ("_to", "_from")

def nuke_count(self, instance, **kwargs):
    cache_key = 'new_friendships_list_for_%s' % (self._to_id.pk)
    cache.delete(cache_key)
    
post_save.connect(nuke_count, Friendship)
post_delete.connect(nuke_count, Friendship)

class UserProfile(models.Model):
    
    
    first_name = models.CharField(u'имя', max_length=100, null=True, db_index=True)
    last_name = models.CharField(u'фамилия', max_length=100, null=True, db_index=True)
    birth_date = models.DateField(u'дата рождения', null=True, blank=True)
    gender = models.CharField(u'пол', choices=GENDER_CHOICES, null=True, max_length=1, blank=True)
    marital_status = models.CharField(u'семейное положение', choices=MARITAL_CHOICES, null=True, max_length=1, blank=True)
    political_views = models.CharField(u'политические взгляды', choices=POLITICAL_CHOICES, null=True, max_length=1, blank=True)
    religious_views = models.CharField(u'религиозные взгляды', choices=RELIGIOUS_CHOICES, null=True, max_length=1, blank=True)
    contact_L0Object = models.ForeignKey(L0Object, verbose_name=u'страна', null=True, blank=True)
    contact_L1Object = models.ForeignKey(L1Object, verbose_name=u'область', null=True, blank=True)
    contact_L2Object = models.ForeignKey(L2Object, verbose_name=u'район', null=True, blank=True)
    contact_L34Object = models.ForeignKey(L34Object, verbose_name=u'город', null=True, blank=True)
    contact_email = models.EmailField(u'электронная почта', blank=True, null=True)
    contact_phone = models.CharField(u'дом. телефон', max_length=20, null=True, blank=True)
    contact_mobilephone = models.CharField(u'моб. телефон', max_length=20, null=True, blank=True)
    contact_icq = models.CharField(u'ICQ', max_length=12, null=True, blank=True)
    contact_gtalk = models.CharField(u'GTalk', max_length=100, null=True, blank=True)
    contact_jabber = models.CharField(u'jabber', max_length=100, null=True, blank=True)
    contact_homepage = models.URLField(u'домашняя страница', null=True, blank=True)
    friends = models.ManyToManyField('UserProfile', verbose_name=u'друзья', related_name='friends', symmetrical=True)
    places = models.ManyToManyField(Place, verbose_name=u'места', related_name='places')
    senior = models.ForeignKey('UserProfile', verbose_name=u'вышестоящий', null=True, blank=True)
    position = models.ForeignKey(Position, verbose_name=u'должность', null=True, blank=True, db_index=True)
    user = models.ForeignKey(User, verbose_name=u'пользователь', unique=True, related_name='user')
        
    def __unicode__(self):
        return unicode(self.first_name) + u' ' + unicode(self.last_name)
        
    def get_friends_list(self):
        cache_key = 'friends_list_for_%s' % (self.pk) 
        friends_list = cache.get(cache_key)
        if friends_list is None:
            friends_list = self.friends.all()
            cache.set(cache_key, friends_list)
        return friends_list

    def get_places_list(self):
        cache_key = 'places_list_for_%s' % (self.pk) 
        places_list = cache.get(cache_key)
        if places_list is None:
            places_list = self.places.all()
            places_list = places_list.select_related()
            cache.set(cache_key, places_list)
        return places_list
    
    def get_friendship_senders_list(self):
        return [f._from for f in Friendship.objects.select_related().filter(_to__id__exact=self.pk)]
        
    def get_full_name(self):
        return unicode(self.first_name)+u' '+unicode(self.last_name)
        
    class Meta:
        verbose_name = u'профиль'
        verbose_name_plural = u'профили'
        
def nuke_friends_list(self, instance, **kwargs):
    cache_key = 'friends_list_for_%s' % (self.pk)
    cache.delete(cache_key)
    
def nuke_places_list(self, instance, **kwargs):
    cache_key = 'places_list_for_%s' % (self.pk)
    cache.delete(cache_key)
    
post_save.connect(nuke_friends_list, UserProfile)
post_delete.connect(nuke_friends_list, UserProfile)
post_save.connect(nuke_places_list, UserProfile)
post_delete.connect(nuke_places_list, UserProfile)
    